package com.hctforgreen.greenservice.utils.irremote;

import android.content.Context;
import android.hardware.ConsumerIrManager;

public class GoogleIrDevice{
	ConsumerIrManager consumerIrManager;
	private int f;
	private int[] pattern;
	private Thread sendThread=null;
	private Thread bufferThread=null;
	private long delayTime=700;;
	public GoogleIrDevice(Context context) {
		consumerIrManager =(ConsumerIrManager)context.getSystemService(Context.CONSUMER_IR_SERVICE);
		sendThread=new Thread(sendRunnable);
		bufferThread=new Thread(bufferRunnable);
	}
	/**
	 *红外信号发射
	 * @param paramString
	 * 发送的红外频率和数据
	 */
	public synchronized void sendIrCode(String paramString) {
		String str[] = paramString.split(",");
		int length=str.length;
//		if(ACContollerService.airColType>0)length=75;//兼容商用空调A码
		int param[] = new int[length - 1];
		for (int i = 1; i < length; i++) {
			param[i - 1] = Integer.parseInt(str[i]);
			delayTime+=param[i-1];//累计延时周期
		}
		delayTime=delayTime*27/1000;//将延时周期转换为以毫秒为单位的时间
		f=Integer.parseInt(str[0]);
		pattern=null;
		pattern=param;
		if(!bufferThread.isAlive()){
			bufferThread=new Thread(bufferRunnable);
			bufferThread.start();
		}
	}
	Runnable sendRunnable= new Runnable(){
		public void run() {
			// TODO Auto-generated method stub
			long sendDelayTime=delayTime;
			if(pattern!=null)consumerIrManager.transmit(f, pattern);

			//红外发射延时
			try {
				Thread.sleep(sendDelayTime);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		  
	  };
	Runnable bufferRunnable= new Runnable(){
		public void run() {
			// TODO Auto-generated method stub
			if(sendThread!=null){
				while(sendThread.isAlive());
				sendThread=new Thread(sendRunnable);
				sendThread.start();
			}
		}
		  
	  };
}